<?php

namespace App\Http\Controllers;

use App\Events\OrderShipped;
use App\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Yansongda\LaravelPay\Facades\Pay;

class CounterController extends Controller
{

    public function __construct()
    {
        $this->middleware(['oauth'])->only('wechat');
    }

    public function index()
    {
        // 如果需要收银台功能  在此处显示
    }

    public function wechat(Request $request)
    {
        $this->validate($request, [
            'order_no' => 'required'
        ]);

        $orderNo = $request->get('order_no');
        $order = Order::where('order_no', $orderNo)->first();

//        $user = Auth::user();
//        if ($order->user_id != $user->id) {
//            return $this->error('订单和用户不匹配');
//        }
        if (!$order->isNeedToPay()) {
            return $this->error('订单已经支付');
        }

        $redirect = request()->get('redirect_url', route('user.index'));
        $back = request()->get('back_url', $redirect);


        //如果是本地环境  直接更改订单状态 触发订单成功事件
        if (config('app.env') == 'local' || config('app.env') == 'testing') {
            $order->paid();
            event(new OrderShipped($order));//触发订单支付事件
            return redirect($redirect);
        }

        $socialite = session('socialite');
        if (!$socialite) {
            return $this->error('请用微信浏览器打开');
        }

        $openId = @$socialite->getOpenid();

        if (!$openId) {
            return $this->error('请用微信浏览器打开');
        }

        $fee = $order->getPayFee();

        $payData = [
            'out_trade_no' => $order->order_no,
            'body' => $order->body,
            'total_fee' => $fee,
            'openid' => $openId,
        ];
        $package = Pay::wechat()->mp($payData);
        return view('counter.wechat', compact('package', 'redirect', 'back'));
    }


    public function notify(Request $request)
    {
        info('notify begin');
        $wechat = Pay::wechat();
        if ($orderCollection = $wechat->verify()) {
            $orderNo = $orderCollection->get('out_trade_no');
            info('notify verify success,order_no' . $orderNo);
            $order = Order::where('order_no', $orderNo)->orderBy('created_at', 'desc')->first();
            if ($order->isNeedToPay()) {
                info('fire order event');
                $order->paid();
                event(new OrderShipped($order));//触发订单支付事件
                return redirect(route('user.index'));
            }
            return $wechat->success();
        } else {
            info('wechat notify verify fail' . json_encode($request->all()));
        }
    }

}
